package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.CustomerInfoApiService;
import com.yixun.qfbao.apidto.AddOrEditCustomerInfoReqDto;
import com.yixun.qfbao.model.CustomerInfo;
import com.yixun.qfbao.model.dto.CustomerInfoDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.service.CustomerInfoService;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.enums.GenderEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class CustomerInfoApiServiceImpl implements CustomerInfoApiService {

	private static final Logger logger = LoggerFactory.getLogger(CustomerInfoApiServiceImpl.class);

	@Autowired
	CustomerInfoService customerInfoService;
	@Autowired
	CustomerPremisesService customerPremisesService;

	@Override
	public CustomerInfoDto addOrEditCustomerInfo(AddOrEditCustomerInfoReqDto reqDto) {
		CustomerInfoDto customerInfoDto = new CustomerInfoDto();
		customerInfoDto.setCpId(reqDto.getCpId());
		CustomerInfo customerInfo = customerInfoService.selectByDto(customerInfoDto);
		CustomerPremises customerPremises = customerPremisesService.selectById(reqDto.getCpId());
		BeanUtils.copyProperties(reqDto, customerInfoDto);
		if(Objects.nonNull(customerInfo)){
			// 存在，修改客戶信息
			customerInfoDto.setId(customerInfo.getId());
			customerInfoDto.setPhone(customerPremises.getMobile());
			customerInfoDto.setSex(reqDto.getGenderName());
			customerInfoService.update(customerInfoDto);
		}else{
			// 不存在，新增客戶信息
			customerInfoDto.setPhone(customerPremises.getMobile());
			customerInfoDto.setSex(reqDto.getGenderName());
			customerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			customerInfoService.create(customerInfoDto);
		}
		// 修改报备信息
		String genderName = reqDto.getGenderName();
		String name =reqDto.getName();
		String adviserUuid = reqDto.getAdviserUuid();
		if(Objects.nonNull(customerPremises)){
			CustomerPremisesDto cpDto = new CustomerPremisesDto();
			cpDto.setId(customerPremises.getId());
			if(GenderEnum.MALE.getDes().equals(genderName)){
				cpDto.setGender(GenderEnum.MALE.getNo());
			}else if(GenderEnum.FEMALE.getDes().equals(genderName)){
				cpDto.setGender(GenderEnum.FEMALE.getNo());
			}
			cpDto.setName(name);
			cpDto.setAdviserUuid(adviserUuid);
			customerPremisesService.update(cpDto);
		}
		return customerInfoDto;
	}
}
